package com.financing.wap.web.controller.api;

import com.financing.wap.common.ImgUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.dto.ActivitesDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.util.WechatUtil;
import com.financing.wap.web.controller.BaseController;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 微信API
 * 
 * @author lisu
 *
 */
@Controller("weixinSTController")
@RequestMapping("/api/wechatST")
public class WeixinSTController extends BaseController {

	Logger logger = Logger.getLogger(getClass());

	public static final String appid = PropertiesUtils.getValue("jcs_appid");

	public static final String secret = PropertiesUtils.getValue("jcs_secret");

	public static final String ACAPPID = PropertiesUtils.getValue("ACAPPID");

	public static final String ACURL = PropertiesUtils.getValue("ACURL");

	public static final String ALLURL = PropertiesUtils.getValue("ALLURL");

	public static final String ACSTATE = PropertiesUtils.getValue("ACSTATE");

	public static final String SDURL = PropertiesUtils.getValue("SDURL");

	public static final String fileBaseDir = PropertiesUtils.getValue("fileDirST");


	/**
	 * 微信授权登录
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/wxAuthLogin")
	public void wxAuthLogin(HttpServletRequest request, HttpServletResponse response) {

		try {

			String sendRedirect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ACAPPID + "&redirect_uri=" + ALLURL +
					"&response_type=code&scope=snsapi_userinfo&state="+ ACSTATE +"#wechat_redirect";
			logger.info("================sendRedirect:"+sendRedirect);

			response.sendRedirect(sendRedirect);
		} catch (Exception e) {
			logger.error("wxAuthLogin error!", e);
		}
	}
	/**
	 * 公众-用户在微信客户端中访问第三方网页回调方法 - st
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/mpback")
	public void mpback(HttpServletRequest request, HttpServletResponse response) {


		// 第一步：请求CODE
		logger.info("in stmpback one get CODE.....................");

		String code = request.getParameter("code");

		if (StringUtil.isNullOrEmptyStr(code)) {
			logger.error("in stmpback one get CODE.is null..");
			return ;
		}

		// 第二步：通过code获取access_token
		logger.info("in stmpback two get AccessToken..............");

		Map<String, Object> map = WechatUtil.getOpenAccessToken(appid, secret,
				code);

		if (map == null) {
			logger.error("in stmpback one get getOpenAccessToken.is null..");
			return ;
		}

		String access_token = (String) map.get("access_token");
		String openid = (String) map.get("openid");

		// 第三步：通过access_token调用接口
		logger.info("in stmpback three get Userinfo...............");

		FaUserWechatDTO bean = WechatUtil.getOpenUserinfo(access_token, openid);

		if (bean == null || StringUtil.isNullOrEmptyStr(bean.getOpenid())) {
			logger.error("in stmpback one get getOpenAccessToken.is null..");
		}
		String fileName = "";
		if(StringUtils.isNotBlank(bean.getHeadimgurl())){
			fileName = "/upload/act/"+openid+".jpg";
			String headimgrl = bean.getHeadimgurl().replace("/64","/0");
			logger.info("in stmpback fileName:"+fileBaseDir+fileName);
			logger.info("in stmpback headimgrl:"+headimgrl);
			ImgUtil.downloadPicture(headimgrl,fileBaseDir+fileName);

		}
		logger.info("in stmpback bean:"+bean.getHeadimgurl());


		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

			String sendRedirect = "http%3a%2f%2f" + SDURL + "%3fimg%3d"+fileName+"%26version%3d"+sdf.format(new Date());

			logger.info("in stmpback sendRedirect:"+sendRedirect);

			response.sendRedirect(URLDecoder.decode(sendRedirect));
		}catch (Exception e){
			logger.error("In stmpback  sendRedirect error!");
		}
		logger.info("In stmpback  end!");

		return ;

	}
}
